package com.ztjava.common.controller;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Ret;
import com.jfinal.upload.UploadFile;
import com.ztjava.common.Common;
import com.ztjava.common.service.FilesService;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.member.ApiClient;
import com.ztjava.core.interceptor.CoreInterceptor;
import com.ztjava.core.interceptor.FilesInterceptor;
import com.ztjava.core.tool.UploadTool;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.core.utiliy.RequestUtil;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.ext.auth.bean.AuthSession;
import com.ztjava.ext.auth.tool.AuthTool;

@ControllerClass(path="/common/files",client=ApiClient.class)
@UserController(portal=Constant.P_MEMBER,token=AuthTool.para)
public class FilesApiController extends BaseController {

	private static FilesService filesService = Duang.duang(FilesService.class);
	//不用CoreInterceptor
	@Clear(CoreInterceptor.class)
	@Before({POST.class,FilesInterceptor.class})
	public void doUpload(){
		List<UploadFile> fileList =  getAttr("fileList");
		String directory = getPara("directory","other");
		AuthSession authSession = getAttr(Constant.AUTHSESSION);
		JSONArray files = new JSONArray();
		String type = ViewTool.param(Common.COMMON_FILES_TYPE,Common.local);
		for(int i=0;i<fileList.size();i++){
			Ret result = UploadTool.normalUpload(fileList.get(i), directory,authSession.getId());
			
			JSONObject item = new JSONObject();
			item.put(Constant.RESULT, result.getStr(Constant.RESULT));
			item.put(Constant.MESSAGE, result.getStr(Constant.MESSAGE));
			item.put("name", result.getStr("name"));
			item.put("parameter", result.getStr("parameter"));
			if(result.getStr(Constant.RESULT).equals(Constant.SUCCESS)){
				filesService.insertInfo(type, result, authSession.getId());
				item.put("domain", RequestUtil.getDomain(getRequest()));
				item.put("filePath", result.getStr("filePath"));
				item.put("ext", result.getStr("ext"));
				files.add(item);
			}else {
				files.add(item);
			}
		}
		setAttr(Constant.RESULT, Constant.SUCCESS);
		setAttr(Constant.MESSAGE, "操作成功！");
		setAttr("files", files);
		renderJson(new String[]{Constant.RESULT,Constant.MESSAGE,"files"});
	}
}
